package com.youpai.platform.user.service.service.transaction;

import com.youpai.platform.chat.service.entity.dto.ChatAccountDTO;
import com.youpai.platform.chat.service.service.ChatAccountFacadeInterface;
import com.youpai.platform.common.constant.BizConstant;
import com.youpai.platform.common.enums.ProcessCodeEnum;
import com.youpai.platform.common.exceptions.BaseBizException;
import com.youpai.platform.common.util.UserNameGenerateUtil;
import com.youpai.platform.common.util.id.IdGenerator;
import com.youpai.platform.user.service.entity.po.UserPO;
import com.youpai.platform.user.service.mapper.UserMapper;
import com.youpai.platform.vulture.common.enums.AppIdEnum;
import com.youpai.platform.wallet.service.service.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @date: 2021/11/24 23:37
 * @author: Anna
 * @version: 1.0
 * @description: 用户相关事务
 */
@Slf4j
@Component
public class UserTransaction {

    @Resource
    private UserMapper userMapper;
    @Resource
    private ChatAccountFacadeInterface chatAccountFacadeInterface;
    @Resource
    private WalletService walletService;

    @Transactional(rollbackFor = Exception.class)
    public UserPO initUserAndGetUserPOByEmail(String userName, String pwd) {
        Long uid = IdGenerator.generateId();
        // 初始化用户信息
        UserPO userPO = buildDefaultUserPOByUid(uid, userName, pwd);
        // 初始化ChatAccount信息
        ChatAccountDTO chatAccountDTO = buildChatAccountDTO(userPO.getUid());
        chatAccountFacadeInterface.createAccount(chatAccountDTO);
        // 创建钱包
        boolean createSuccess = walletService.registerWallet(userPO.getUid());
        if (!createSuccess) {
            throw new BaseBizException(ProcessCodeEnum.REGISTER_WALLET_ERROR);
        }

        // 执行事务
        userMapper.insert(userPO);
        // 初始化账户信息
        return userPO;
    }

    private ChatAccountDTO buildChatAccountDTO(Long uid) {
        return new ChatAccountDTO()
                .setAppId(AppIdEnum.KILA.appId)
                .setUid(uid.toString());
    }

    private UserPO buildDefaultUserPOByUid(Long uid, String userName, String pwd) {
        return new UserPO()
                .setUid(uid)
                .setUserName(userName)
                .setGender(0)
                .setPwd(pwd)
                .setBirthday(new Date())
                .setAvatar("https://pek3b.qingstor.com/youpai-daka-file/img/-13395831801648453891885.jpg")
                .setNickName(UserNameGenerateUtil.generateUserName())
                .setEmail(userName);
    }

}
